src/views/owner/index.vue
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Delete, Edit, Download } from '@element-plus/icons-vue'
import { suringallApi, addserve, getidserve, updateserve, removeids } from '@/api/owner'
import { getCityList } from '@/api/supplier'
import { ElMessage } from 'element-plus'
// 数据模型
const ruleForm = reactive({
  id: '',
  ownerName: '',         // 货主名称
  cityCode: [],          // 所在城市（数组形式，用于级联选择器回显）
  address: '',           // 详细地址
  contactInfo: '',       // 联系方式
  responsiblePerson: '', // 负责人
  createBy: '',          // 创建人
  createTime: ''         // 创建时间
})

// 表单校验规则
const rules = {
  ownerName: [{ required: true, message: '请输入货主名称', trigger: 'blur' }],
  cityCode: [{ required: true, message: '请选择所在城市', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  contactInfo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  responsiblePerson: [{ required: true, message: '请输入负责人', trigger: 'blur' }]
}

// 搜索条件
const from = reactive({
  ownerName: ''
})

// 表格数据
const tableData = ref([])

// 分页参数
const Page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 城市级联数据
const pcdtada = ref([])

// 对话框控制
const dialogVisible = ref(false)

// 获取城市数据
const fetchCityData = async () => {
  try {
    const res = await getCityList()
    // 检查返回的数据是否存在且为数组
    if (res && res.data && Array.isArray(res.data)) {
      pcdtada.value = formatCityData(res.data)
    } else {
      console.warn('城市数据格式不正确:', res)
      // 即使格式不正确，也尝试处理数据
      if (res && Array.isArray(res)) {
        pcdtada.value = formatCityData(res)
      } else {
        pcdtada.value = []
      }
    }
  } catch (error) {
    ElMessage.error('获取城市数据失败')
    console.error('获取城市数据失败:', error)
    pcdtada.value = []
  }
}

// 格式化城市数据
const formatCityData = (data) => {
  if (!Array.isArray(data)) return []
  
  return data.map(item => ({
    value: item.id,
    label: item.name,
    children: item.children && Array.isArray(item.children) && item.children.length > 0
      ? formatCityData(item.children)
      : []
  }))
}

// 获取城市名称显示
const getCityName = (code) => {
  if (!code) return ''
  
  const findCityName = (options, value) => {
    for (const item of options) {
      if (item.value === value) {
        return item.label
      }
      if (item.children && item.children.length > 0) {
        const result = findCityName(item.children, value)
        if (result) return result
      }
    }
    return ''
  }
  
  // 处理数组或单个值
  const value = Array.isArray(code) ? code[code.length - 1] : code
  return findCityName(pcdtada.value, value)
}

// 获取对话框标题
const getTitle = () => {
  return ruleForm.id ? '编辑货主' : '新增货主'
}

// 获取列表数据
const fetchList = async () => {
  try {
    const res = await suringallApi(from.ownerName, Page.value, pageSize.value)
    if (res && res.data && res.data.records) {
      tableData.value = res.data.records
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取货主列表失败')
    console.error('获取货主列表失败:', error)
    tableData.value = []
    total.value = 0
  }
}

// 新增
const add = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑
const getid = async (id) => {
  try {
    const res = await getidserve(id)
    console.log('获取到的货主信息:', res)
    
      const data = res
      
      // 清空表单
      resetForm()
      
      // 设置ID
      ruleForm.id = data.id || ''
      
      // 设置其他字段
      ruleForm.ownerName = data.ownerName || ''
      ruleForm.address = data.address || ''
      ruleForm.contactInfo = data.contactInfo || ''
      ruleForm.responsiblePerson = data.responsiblePerson || ''
      ruleForm.createBy = data.createBy || ''
      ruleForm.createTime = data.createTime || ''
      
      // 处理城市代码回显
      if (data.cityCode) {
        // 查找城市代码对应的路径
        const cityPath = findCityPath(pcdtada.value, data.cityCode)
        ruleForm.cityCode = cityPath || []
      } else {
        ruleForm.cityCode = []
      }
      
      console.log('设置后的表单数据:', ruleForm)
      dialogVisible.value = true
    
  } catch (error) {
    ElMessage.error('获取货主信息失败: ' + error.message)
    console.error('获取货主信息失败:', error)
  }
}

// 查找城市路径
const findCityPath = (options, targetValue, path = []) => {
  if (!Array.isArray(options)) return null
  
  for (const item of options) {
    const currentPath = [...path, item.value]
    
    if (item.value === targetValue) {
      return currentPath
    }
    
    if (item.children && item.children.length > 0) {
      const result = findCityPath(item.children, targetValue, currentPath)
      if (result) {
        return result
      }
    }
  }
  return null
}

// 删除单条
const removes = async (id) => {
  try {
    await removeids(id)
    ElMessage.success('删除成功')
    fetchList()
  } catch (error) {
    ElMessage.error('删除失败')
    console.error('删除失败:', error)
  }
}

// 批量删除
const remove = async (selection) => {
  if (selection.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  try {
    const ids = selection.map(item => item.id)
    // 如果API支持批量删除，可以调用批量删除接口
    for (const id of ids) {
      await removeids(id)
    }
    ElMessage.success('删除成功')
    fetchList()
  } catch (error) {
    ElMessage.error('删除失败')
    console.error('删除失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  Page.value = 1
  fetchList()
}

// 重置
const handleReset = () => {
  from.ownerName = ''
  Page.value = 1
  fetchList()
}

// 提交表单
const submitForm = async () => {
  try {
    // 处理表单数据
    const formData = {
      ownerName: ruleForm.ownerName,
      address: ruleForm.address,
      contactInfo: ruleForm.contactInfo,
      responsiblePerson: ruleForm.responsiblePerson,
      createBy: ruleForm.createBy
    }
    
    // 处理城市代码（取数组最后一个值）
    if (Array.isArray(ruleForm.cityCode) && ruleForm.cityCode.length > 0) {
      formData.cityCode = ruleForm.cityCode[ruleForm.cityCode.length - 1]
    } else {
      formData.cityCode = null // 如果没有选择城市，设置为null
    }
    
    if (ruleForm.id) {
      // 更新时包含ID
      formData.id = ruleForm.id
      await updateserve(formData)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await addserve(formData)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    resetForm()
    fetchList()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.response?.data?.message || error.message))
    console.error('保存失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  ruleForm.id = ''
  ruleForm.ownerName = ''
  ruleForm.cityCode = []
  ruleForm.address = ''
  ruleForm.contactInfo = ''
  ruleForm.responsiblePerson = ''
  ruleForm.createBy = ''
  ruleForm.createTime = ''
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchList()
}
const handleCurrentChange = (val) => {
  Page.value = val
  fetchList()
}
const clean = () => {
  from.ownerName = ''
  fetchList()
  

}


// 组件挂载时获取数据
onMounted(() => {
  fetchList()
  fetchCityData()
})
</script>

<template>
  <div>
 <div class="form">
  <el-form :inline="true" :model="form"  style="max-width: 600px">
    <el-form-item label="货主名称">
      <el-input v-model="from.ownerName" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="clean">取消</el-button>
    </el-form-item>
  </el-form>
   <el-button type="primary"  @click="add"  >新增</el-button>
   </div>
  <div class="table">
  <el-table :data="tableData"  border style="width: 100%">
    <el-table-column type="index" label="#" width="50" />
    <el-table-column prop="ownerName" label="货主名称" width="180" />
    <el-table-column label="所在城市" width="120">
      <template #default="scope">
        <span>{{ getCityName(scope.row.cityCode) }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="address" label="详细地址" width="200" />
    <el-table-column prop="contactInfo" label="联系方式" width="120" />
    <el-table-column prop="responsiblePerson" label="负责人" width="120" />
    <el-table-column prop="createTime" label="创建时间" width="160" />
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button :icon="Edit" @click="getid(scope.row.id)" circle />
        <el-button :icon="Delete" @click="removes(scope.row.id)" circle />
      </template>
    </el-table-column>
  </el-table>
  </div>
  <div class="page">
  <el-pagination 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange"
      :current-page="currentPage" 
      :page-sizes="[5, 10, 20]" 
      :page-size="pageSize"
      :total="total" 
      layout="total, sizes, prev, pager, next, jumper"
    />
    </div>
  <el-dialog
    v-model="dialogVisible"
    :title="getTitle()"
    width="500"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      style="max-width: 800px"
    >
      <el-form-item label="货主名称" prop="ownerName">
        <el-input v-model="ruleForm.ownerName" />
      </el-form-item>
      <el-form-item label="所在城市" prop="cityCode">
        <el-cascader
          v-model="ruleForm.cityCode"
          :options="pcdtada"
          :props="{ checkStrictly: true, value: 'value', label: 'label', children: 'children' }"
          placeholder="请选择所在城市"
          clearable
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="ruleForm.address" />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input v-model="ruleForm.contactInfo" />
      </el-form-item>
      <el-form-item label="负责人" prop="responsiblePerson">
        <el-input v-model="ruleForm.responsiblePerson" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>
<style scoped>
.form {
  margin-left: 200px;
}
.table {
  margin-top: 20px;
  margin-left: 200px;
}
.page {
  margin-top: 20px;
  margin-left: 200px;
}
</style>
